#!/usr/bin/env python
# encoding: utf-8

import psycopg2
import redis
import datetime

conn = psycopg2.connect(
    database="ass",
    user="postgres",
    password="postgres",
    host="10.0.0.39",
    port=5432
)


class StockInfo(object):
    def __init__(self):
        self.conn = conn
        cursor = self.conn.cursor()

        cursor.execute("select code, name, market, profession from t_stockinfo;")
        self.stocks = dict()
        for item in cursor.fetchall():
            self.stocks[item[0]] = {
                "name": item[1],
                'market': item[2],
                'profession': item[3]
            }

        cursor.close()

    def insert_history(self, datas):
        def _etl_csv(_x):
            def _add_signal(_str):
                return f"'{_str}'"
            _line = ",".join(list(map(lambda x: _add_signal(x), _x)))
            return "(" + _line + ")"

        cursor = self.conn.cursor()
        cursor.execute("INSERT INTO t_stock_day VALUES " + ",".join(list(map(_etl_csv, datas))))
        self.conn.commit()
        cursor.close()

    def all_stock_day_start(self):
        cursor = self.conn.cursor()
        cursor.execute("SELECT code, max(date) from t_stock_day GROUP BY code;")
        ret = dict()
        for code, date in cursor.fetchall():
            ret[code] = (datetime.timedelta(days=1)+date).strftime("%Y-%m-%d")
        cursor.close()
        return ret

    def execute(self, sql):
        cursor = self.conn.cursor()
        cursor.execute(sql)
        ret = cursor.fetchall()
        cursor.close()
        return ret

    def all_stocks(self):
        return self.stocks.keys()

    def name(self, code):
        return self.stocks[code]['name']

    def market(self, code, isNumber=False):
        if isNumber:
            return 0 if self.stocks[code]['market'] == 'sh' else 1
        return self.stocks[code]['market']

    def profession(self, code):
        return self.stocks[code]['profession']

    def all_quota(self):
        cursor = self.conn.cursor()
        cursor.execute("SELECT id, name, formula, sources, market from t_quota where status = 1;")
        ret = dict()
        for qid, qname, qformula, qsources, qmarket in cursor.fetchall():
            ret[qid] = {
                'id': qid,
                'name': qname,
                'formula': qformula,
                'sources': qsources,
                'market': qmarket
            }
        cursor.close()
        return ret


class Outer(object):
    instance = None

    def __init__(self, host="10.0.0.39", port=6379, channel="MarketUpdateSignal"):
        self.pool = redis.ConnectionPool(host=host, port=port, password='lt@3600', db='9')
        self.rds = redis.Redis(connection_pool=self.pool)
        self.channel = channel.split(',')
        self.ps = self.rds.pubsub()
        self.ps.subscribe(self.channel)

    @classmethod
    def get_cli(cls, host="10.0.0.39", port=6379):
        if not cls.instance:
            cls.instance = redis.Redis(host=host, port=port, password='lt@3600', db='9')
        return cls.instance

    def subscribe(self, chs):
        """:type chs:list[str]"""
        self.ps.subscribe(chs)

    def put(self, k, v):
        self.rds.set(k, v)

    def keys(self, k):
        return list(map(lambda x: x.decode(), self.rds.keys(k)))

    def publish(self, msg):
        self.rds.publish(self.channel, msg)

    def set_channel(self, channel):
        self.channel = channel.split(',')
        self.ps = self.rds.pubsub()
        self.ps.subscribe(self.channel)

    def channel(self):
        return self.channel

    def get_ps(self):
        return self.ps

    def get(self, k):
        ret = self.rds.get(k)
        if ret:
            ret = bytes.decode(ret)
            if ret.isdigit():
                return int(ret)
            else:
                try:
                    return float(ret)
                except (Exception, ):
                    return ret
        else:
            return ""


def unit():
    pass


if __name__ == "__main__":
    pass
